package org.javaweb.cms_web.service;

import org.apache.ibatis.annotations.Param;
import org.javaweb.cms_web.mapper.UserMapper;
import org.javaweb.cms_web.model.Enum.RoleType;
import org.javaweb.cms_web.model.LoginTicket;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserService {
    public static final String TICKET = "ticket:";
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private HostHolder hostHolder;

    //通过填写的邮箱查看注册情况
    public boolean addUser(User user) {
        try {
            userMapper.insertUser(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //根据用户实际名称查找用户
    public User findUserByName(String name) {
        return userMapper.getUserByName(name);  // 调用 DAO 层查询用户
    }

    public User findUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    public User authenticate(String username, String password) {
        return userMapper.getUserByNicknameAndPassword(username, password);
    }

    // 检查用户名是否存在
    public User getUserByNickname(String username) {
        return userMapper.getUserByNickname(username);
    }

    //检查邮箱是否已经被使用
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    public Map<String, Object> Login(User user) {
        Map<String, Object> map = new HashMap<>();
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getUserId());
        loginTicket.setTicket(UUID.randomUUID().toString().replaceAll("-", ""));
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + 3600 * 1000));

        String ticketKey = TICKET + loginTicket.getTicket();
        redisTemplate.opsForValue().set(ticketKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    public LoginTicket findLoginTicket(String ticket) {
        String ticketKey = TICKET + ticket;
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
    }

    public User findUserById(int userId) {
        return userMapper.getUserById(userId);
    }

    public List<User> getAllTeamAdmins() {
        return userMapper.getAllTeamAdmins();
    }

    public void Logout() {
        LoginTicket loginTicket = hostHolder.getLoginTicket();
        if (loginTicket != null) {
            loginTicket.setStatus(1);
            String ticketKey = TICKET + loginTicket.getTicket();
            redisTemplate.delete(ticketKey);
        }
    }

    public void createTeamAdmin(User user) {
        user.setRoleType(RoleType.TEAM_ADMIN.getCode());
        user.setStatus(1);
        userMapper.insertUser(user);
    }

    public void deleteUserById(Integer id) {
        userMapper.deleteUser(id);
    }

    public boolean updateUser(User user) {
        int rows = userMapper.updateUser(user);
        return rows > 0;
    }

    //新建用户
    public boolean saveUser(User newuser) {
        int rows = userMapper.insertUser(newuser);
        return rows > 0;
    }

    public List<User> getUsersForReview(Integer teamId) {
        return userMapper.findUsersForReview(teamId);
    }

    /**
     * public class User {
     *
     *     private Integer userId; // 用户ID
     *     private String nickname; // 用户昵称
     *     private String name; // 用户姓名
     *     private String password; // 密码
     *     private String email; // 用户邮箱
     *     private Integer roleType; // 用户角色类型
     *     private String researchDirection; // 研究方向
     *     private String applicationReason; // 申请理由
     *     private Date registrationTime; // 注册时间
     *     private Integer status; // 用户状态
     *     private String phoneNumber; // 用户联系方式
     *     private String academicBackground; // 用户学术背景
     *     private String researchAchievements; // 用户科研成果
     *     private String jobTitle; // 用户职务
     *     private Integer teamId; // 所属团队ID
     *     private String auditInfo; //审核信息
     *     private String securityQuestion; //密保问题
     *     private String securityAnswer; //密保答案
     * }
     * @param user
     * @return
     */
    public boolean updateUserSomeFiled(User user) {
        Integer userId = user.getUserId();
        User user1 = userMapper.getUserById(userId);
        if (user1 == null) {
            return false;
        }
        if (user.getNickname() != null) {
            user1.setNickname(user.getNickname());
        }
        if (user.getEmail() != null) {
            user1.setEmail(user.getEmail());
        }
        if (user.getRoleType() != null) {
            user1.setRoleType(user.getRoleType());
        }
        if (user.getResearchDirection() != null) {
            user1.setResearchDirection(user.getResearchDirection());
        }
        if (user.getApplicationReason() != null) {
            user1.setApplicationReason(user.getApplicationReason());
        }
        if (user.getRegistrationTime() != null) {
            user1.setRegistrationTime(user.getRegistrationTime());
        }
        if (user.getStatus() != null) {
            user1.setStatus(user.getStatus());
        }
        if (user.getPhoneNumber() != null) {
            user1.setPhoneNumber(user.getPhoneNumber());
        }
        if (user.getAcademicBackground() != null) {
            user1.setAcademicBackground(user.getAcademicBackground());
        }
        if (user.getResearchAchievements() != null) {
            user1.setResearchAchievements(user.getResearchAchievements());
        }
        if (user.getJobTitle() != null) {
            user1.setJobTitle(user.getJobTitle());
        }
        if (user.getTeamId() != null) {
            user1.setTeamId(user.getTeamId());
        }
        if (user.getAuditInfo() != null) {
            user1.setAuditInfo(user.getAuditInfo());
        }
        if (user.getSecurityQuestion() != null) {
            user1.setSecurityQuestion(user.getSecurityQuestion());
        }
        if (user.getSecurityAnswer() != null) {
            user1.setSecurityAnswer(user.getSecurityAnswer());
        }
        int rows = userMapper.updateUser(user1);
        return rows > 0;
    }
}
